import {createRouter, createWebHistory, type Router, type RouteRecord, type RouteRecordRaw} from 'vue-router'
import HomeView from '../views/HomeView.vue'
import type {Menu} from "@/types/base.ts";
import {useAuthStore} from "@/stores/auth.ts"
import ResourceUpload from "@/components/upload/ResourceUpload.vue";
import MenuTree from "@/components/menuTree/MenuTree.vue";
import CourseResourse from "@/views/emp/CourseResourse.vue";
import Course from "@/views/courseManagement/Course.vue";
import PaperTest from "@/components/paperTest/PaperTest.vue";

const router : Router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/Login.vue'),
    },
    {
      path: '/resourceUpload',
      name: 'resourceUpload',
      component: ResourceUpload
    },
    {
      path: '/PaperTest',
      name: 'PaperTest',
      component: PaperTest,
      children:[

      ]
    },
    {
      path: '/',
      name: 'home',
      component: HomeView,
      // 重定向
      // redirect:'/index',
      // 主页内部组件
      children: []
    },

    {
      path:'/resourse/:courseId',
      name:'resourse',
      component:CourseResourse
    },

    //   网站404
    {
      path: '/:pathMatch(.*)*',
      // path:'path:*',
      name: 'notFound',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      //@ts-ignore
      component: () => import('../views/NotFound.vue'),
    },
  ],
})
//创建动态路由
// 1.预加载所有组件
const modules = import.meta.glob('../views/**/*.vue')


// 2.加载路由方法
let isDynamicRoutersAdded = false // 1 标记：动态路由是否已添加
export function createDynamicRouters(menus:Menu[]|null|undefined) : void {
  if (!menus || !Array.isArray(menus)) return
  menus.forEach(menu => {

    menu.children?.forEach(child => {
      if (child.type === 'menuitem' &&
          child.component &&
          child.path &&           // 这个判断至关重要！
          typeof child.path === 'string' &&
          child.path.trim() !== ''
      ) {
        // 注意：这里不再将路径转换为相对路径，因为我们现在是作为根路由的子路由
        // 但是菜单数据中的路径可能是绝对路径，我们需要去掉开头的斜杠，使其成为相对路径

        let routePath = child.path.startsWith('/') ? child.path.slice(1) : child.path
        // 处理组件路径：确保格式正确

        let componentPath = child.component
        if (componentPath.startsWith('/')) {
          componentPath = componentPath.substring(1)
        }
        //const fullComponentPath = `/src/views/${componentPath}.vue`
        //使用相对路径，需要在vite.config.js中配置base根路径，相对于当前的js文件的路径
        const fullComponentPath = `../views/${componentPath}.vue`
        // 直接从 modules 获取组件
        const component = modules[fullComponentPath]
        const route: RouteRecordRaw = {
          path: routePath,
          name: child.menuName,
          component: component,
          meta: {
            perms: child.perms,
            icon: child.icon,
            menuId: child.id
          }
        } as RouteRecordRaw
        //防止重复添加
        // 在调用 hasRoute 之前确保 name 存在
        if (child.menuName && !router.hasRoute(child.menuName)) {
          router.addRoute('home', route)
        }
      }
      // 可选：打印警告
      else {
        console.warn('[Router] 忽略无效菜单项:', child.menuName, { path: child.path, component: child.component, type: child.type })
      }
    })
  })
  //2 添加成功后标记为已添加
  isDynamicRoutersAdded = true
}
//全局路由守卫
// 判断是否丢失了动态路由，刷新就丢失，如果丢失了就重新创建
router.beforeEach((to, from, next) => {
  const userStore = useAuthStore()
  // 如果正在前往登录页，直接放行
  if (to.path === '/login') {
    next()
    return
  }
  // 如果用户已登录但动态路由丢失
  if (userStore.token && Array.isArray(userStore.myMenus) && userStore.myMenus.length > 0) {

    //这里的5是静态路由数量
    //if (userStore.userMenus.length > 0 && router.getRoutes().length <= (5 + userStore.userMenus.length)) {
    // 3 关键：只在动态路由尚未添加时才重建
    if (!isDynamicRoutersAdded) {
      console.log('检测到动态路由丢失，重新创建')
      createDynamicRouters(userStore.myMenus)
      next(to.fullPath) // 重新跳转到当前页面
      return
    }
    // 否则：动态路由已添加，直接放行
    next()
    return
  }
  // 用户无 token 或无菜单数据
  if (!userStore.token) {
    // 未登录，跳转登录页
    next('/login')
    return
  }
  // 默认放行
  next()
})



export default router
